/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.util.lang;

import java.util.Arrays;

/**
 * 数组工具类
 *
 * @author zeng
 */
public class ArrayUtils {

  /**
   * 判断数据是否为空
   *
   * @param array {@link Object} 长度
   * @return {@link Boolean} 数组为null或者长度为0时，返回 false
   */
  public static boolean isEmpty(Object[] array) {
    return array == null || array.length == 0;
  }

  /**
   * 判断数组是否不为空
   *
   * @param array {@link Object} 数组
   * @return {@link Boolean} 数组对象内含有任意对象时返回 true
   * @see ArrayUtils#isEmpty(Object[])
   */
  public static boolean isNotEmpty(Object[] array) {
    return !isEmpty(array);
  }

  /**
   * 对象是否为数组对象
   *
   * @param obj 对象
   * @return 是否为数组对象，如果为{@code null} 返回false
   */
  public static boolean isArray(Object obj) {
    return null != obj && obj.getClass().isArray();
  }

  /**
   * 数组或集合转String
   *
   * @param obj 集合或数组对象
   * @return 数组字符串，与集合转字符串格式相同
   */
  public static String toString(Object obj) {
    if (null == obj) {
      return null;
    }

    if (obj instanceof long[]) {
      return Arrays.toString((long[]) obj);
    } else if (obj instanceof int[]) {
      return Arrays.toString((int[]) obj);
    } else if (obj instanceof short[]) {
      return Arrays.toString((short[]) obj);
    } else if (obj instanceof char[]) {
      return new String((char[]) obj);
    } else if (obj instanceof byte[]) {
      return Arrays.toString((byte[]) obj);
    } else if (obj instanceof boolean[]) {
      return Arrays.toString((boolean[]) obj);
    } else if (obj instanceof float[]) {
      return Arrays.toString((float[]) obj);
    } else if (obj instanceof double[]) {
      return Arrays.toString((double[]) obj);
    } else if (ArrayUtils.isArray(obj)) {
      // 对象数组
      try {
        return Arrays.deepToString((Object[]) obj);
      } catch (Exception ignore) {
        // ignore
        return obj.toString();
      }
    }

    return obj.toString();
  }
}
